package sql;


import  java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;

public class LoginJDBC { //连接数据库类
    static  JDBC_T jdbc_t;
//    public static void main(String[] args) {
//        jdbc_t = new JDBC_T();
//        if(jdbc_t.is_conn()){
//            login("李华","1");
//        }
//    }
    public void initialize(){
        jdbc_t = new JDBC_T();
        if(jdbc_t.is_conn()){
            System.out.println("登陆时连接数据库成功");
        }
    }

    public  static Integer login(String username,String password){ //传入参数的login函数
//        String find_pass = "SELECT pass from users where username ="+" "+username;
        String find_pass=MessageFormat.format("SELECT * from users where username ={0}{1}{0}",'"',username);
        try{
            PreparedStatement preparedStatement = jdbc_t.getConn().prepareStatement(find_pass);
            ResultSet resultSet = preparedStatement.executeQuery();

            if(!resultSet.next()) {   //检查有没有此用户
                System.out.println(MessageFormat.format("无此用户名{0}",username));
            }
            else {
                //System.out.println(resultSet.getString(""));
                if (resultSet.getString("username").equals(username) && resultSet.getString("pass").equals(password)) {
                    System.out.println("login Successfully!!!");
                    String userkind=resultSet.getString("privilege");
                    if(userkind.equals("admin")){
                        System.out.println(MessageFormat.format("Welcome admin {0}!! ",username));
                        return 1;
                    }if(userkind.equals("student")){
                        System.out.println(MessageFormat.format("Welcome student{0}!! ",username));
                        return 2;
                    }if(userkind.equals("teacher")){
                        System.out.println(MessageFormat.format("Welcome teacher {0}!! ",username));
                        return 3;
                    }
                }
                else {
                    System.out.println(MessageFormat.format("密码错误 {0}!! ",username));
                    return -1;
                }
            }
        }catch (Exception sqle){
            sqle.printStackTrace();
        }
        return 0;
    }
}
